package cn.wolfcode.wolf2w.note.service.impl;

import cn.wolfcode.wolf2w.common.core.constant.SecurityConstants;
import cn.wolfcode.wolf2w.common.core.domain.R;
import cn.wolfcode.wolf2w.member.api.RemoteUserInfoService;
import cn.wolfcode.wolf2w.member.api.domain.UserInfo;
import cn.wolfcode.wolf2w.note.api.domain.NoteComment;
import cn.wolfcode.wolf2w.note.mapper.NoteCommentMapper;
import cn.wolfcode.wolf2w.note.query.NoteCommentQuery;
import cn.wolfcode.wolf2w.note.service.INoteCommentService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 游记评论Service业务层处理
 *
 * @author dalang
 * @date 2023-11-27
 */
@Service
@Transactional
public class NoteCommentServiceImpl extends ServiceImpl<NoteCommentMapper, NoteComment> implements INoteCommentService {
    @Autowired
    private RemoteUserInfoService remoteUserInfoService;

    @Override
    public IPage<NoteComment> queryPage(NoteCommentQuery qo) {
        IPage<NoteComment> page = new Page<>(qo.getCurrentPage(), qo.getPageSize());
        lambdaQuery()
                .eq(qo.getNoteId() != null, NoteComment::getNoteId, qo.getNoteId())
                .page(page);

        for (NoteComment comment : page.getRecords()) {
            R<UserInfo> ret = remoteUserInfoService.getOne(comment.getUserId(), SecurityConstants.INNER);
            if (ret != null && R.isSuccess(ret)) {
                comment.setUser(ret.getData());
            }

            if (comment.getRefId() != null) {
                NoteComment refComment = super.getById(comment.getRefId());
                R<UserInfo> refRet = remoteUserInfoService.getOne(refComment.getUserId(), SecurityConstants.INNER);
                if (refRet != null && R.isSuccess(refRet)) {
                    refComment.setUser(refRet.getData());
                }
                comment.setRefComment(refComment);
            }
        }
        return page;
    }

    @Override
    public List<NoteComment> newCommontsTop10() {
        List<NoteComment> list = lambdaQuery().orderByDesc(NoteComment::getCreateTime).last("limit 10").list();
        for (NoteComment comment : list) {
            R<UserInfo> ret = remoteUserInfoService.getOne(comment.getUserId(), SecurityConstants.INNER);
            if (ret!=null && R.isSuccess(ret)) {
                comment.setUser(ret.getData());
            }
        }
        return list;
    }
}
